package com.wisenet.controller.web.wx;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.wisenet.controller.PlatformController;
import com.wisenet.entity.MenuInfo;
import com.wisenet.entity.User;
import com.wisenet.entity.WeixinPubno;
import com.wisenet.service.wx.MenuInfoService;
import com.wisenet.service.wx.WeiXinPubnoService;
import com.wisenet.service.wxpubno.WeixinService;
import com.wisenet.wx.util.WeixinUtil;

/**
 * 公众号自定义菜单控制类
 * @author fzh
 */
@Controller
@RequestMapping("/menu")
public class MenuInfoController extends PlatformController {
	@Autowired
	private WeixinService weixinService;
	@Autowired
	private MenuInfoService menuInfoService;
	@Autowired
	private WeiXinPubnoService weiXinPubnoService;
	
	private static final Logger logger = Logger.getLogger(MenuInfoController.class);
	
	/**
	 * 自定义菜单页面
	 * @return
	 */
	@RequestMapping("/wxtreeUI")
	public ModelAndView menuInfoUI(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView(getBasePath() + "wxtree");
		User user = getSessionUser(request);
		if (user != null) {
			List<WeixinPubno> list = weiXinPubnoService.getList(user.getUsername(), "pubno");
			mav.addObject(LIST, list);
		}
		return mav;
	}
	
	/**
	 * 获取菜单
	 * @param pubno
	 * @return
	 */
	@RequestMapping("/wxmenu")
	public @ResponseBody JSONObject getMenuJson(String pubno) {
		JSONObject json = getJsonResult(pubno);
		if (json.getBoolean(SUCCESS)) {
			List<MenuInfo> list = menuInfoService.findByWxNo(pubno);
			if (list != null) {
				MenuInfo rootMenu = new MenuInfo();
				rootMenu.setId(0);
				rootMenu.setMenuId(0);
				rootMenu.setParentMenuId(0L);
				rootMenu.setName("自定义菜单列表");
				list.add(0, rootMenu);
				json.put(LIST, JSONObject.toJSON(list));
			}
		}
		return json;
	}
	
	/**
	 * 保存或修改菜单
	 * @param menuInfo
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdateMenu", method = RequestMethod.POST)
	public ModelAndView saveOrUpdateMenu(MenuInfo menuInfo) {
		ModelAndView mav = new ModelAndView("redirect:/menu/wxtreeUI");
		logger.info(JSONObject.toJSON(menuInfo));
		try {
			menuInfo.setCreateTime(new Date());
			menuInfo.setWeixinPublicNo(menuInfo.getWeixinPublicNo());
			menuInfoService.saveOrUpdateMenu(menuInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	/**
	 * 发布菜单，前端组装菜单JSON数据
	 * @param pubno
	 * @param jsondata
	 * @return
	 */
	@RequestMapping(value = "/createMenu", method = RequestMethod.POST)
	public @ResponseBody JSONObject createMenu(String pubno, String jsondata) {
		JSONObject json = getJsonResult(pubno, jsondata);
		if (!json.containsKey(SUCCESS)) {
			return json;
		}
		// 创建菜单
		jsondata = jsondata.replaceAll("},]", "}]");
		logger.info("jsondata = " + jsondata);
		
		WeixinPubno wxpListVO = weiXinPubnoService.findByWxNo(pubno);
		if (wxpListVO == null) {
			json.put(RESULT, "公众号不存在");
			return json;
		}
		if (wxpListVO.getAppid() == null || wxpListVO.getAppsecret() == null) {
			json.put(RESULT, "公众号未授权");
			return json;
		}
		String token = weixinService.getToken(wxpListVO.getAppid(), wxpListVO.getAppsecret());
		if (token == null) {
			json.put(RESULT, "获取TOKEN失败");
			return json;
		}
		int result = WeixinUtil.createMenu(jsondata, token);
		json.put(RESULT, result);
		return json;
	}

	/**
	 * 查询图文
	 * @param menuId
	 * @param pubno
	 * @return
	 */
	@RequestMapping("/findImgTxtHtml}")
	public @ResponseBody String findImgTxtHtml(String menuId, String pubno) {
		if (menuId != null) {
			MenuInfo menuInfo = menuInfoService.doFindByMenuId(menuId, pubno);
			if (menuInfo != null) {
				return menuInfo.getRefText();
			}
		}
		return null;
	}

	/**
	 * 删除菜单
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteMenu", method = RequestMethod.POST)
	public @ResponseBody JSONObject deleteMenuById(String id) {
		JSONObject json = getJsonResult(id);
		if (json.containsKey(SUCCESS)) {
			try {
				int result = menuInfoService.delete(Integer.parseInt(id));
				json.put(RESULT, result);
			} catch (Exception e) {
				logger.info("传参有误：id = " + id);
			}
		}
		return json;
	}

	/**
	 * 删除全部节点
	 * @param pubno
	 * @return
	 */
	@RequestMapping("/deleteAllNodes")
	public @ResponseBody int deleteAllNodes(String pubno) {
		menuInfoService.deleteByWxNo(pubno);
		return 1;
	}

	@Override
	protected String getBasePath() {
		return "/menu/menuinfo/";
	}

}
